import { request } from 'umi';
import { message } from 'antd';
import { exportExcel } from '@/chaos/functions/Execl';

export async function add(domain: string, param: any = {}) {
    message.loading('正在添加');
    const { data } = await request(`/manage/${domain}/add`, { data: param });
    if (data) {
        message.success('添加成功');
    }
    return data || false;
}

export async function update(domain: string, mu: string, param: any = {}) {
    message.loading('正在更新');
    const { data } = await request(`/manage/${domain}/update`, { data: { mu, data: param } });
    if (data) {
        message.success('更新成功');
    }
    return data || false;
}

export async function remove(domain: string, mu: string) {
    message.loading('正在删除');
    const { data } = await request(`/manage/${domain}/delete`, { data: { mu } });
    if (data) {
        message.success('删除成功');
    }
    return data || false;
}

export async function page(domain: string, params: any = {}) {
    const { current: pageNum, pageSize, data: param } = params;
    const { page } = await request(`/manage/${domain}/page`, {
        data: { pageNum, pageSize, data: param },
    });
    const { list = [], total = 0 } = page;
    return { data: list, success: true, total };
}

export async function list(domain: string, param: any = {}) {
    const { data } = await request(`/manage/${domain}/list`, { data: param });
    return data || [];
}

export async function one(domain: string, mu: string) {
    const { data } = await request(`/manage/${domain}/one`, { data: { mu } });
    return data || {};
}

export async function submit(method: string, param: any = {}) {
    const { data } = await request(`/manage/${method}`, { data: param });
    return data || false;
}

export async function search(method: string, params: any = {}) {
    const { current: pageNum, pageSize, data: param } = params;
    const { page: pageData } = await request(`/manage/${method}`, {
        data: { pageNum, pageSize, data: param },
    });
    const { list = [], total = 0 } = pageData;
    return { data: list, success: true, total };
}

export async function query(method: string, param: any = {}) {
    const { data } = await request(`/manage/${method}`, { data: param });
    return data;
}

export async function searchExport(
    method: string,
    header: any,
    filename: string = 'demo',
    data: any,
) {
    let pageNum = 1;
    let res;
    do {
        /* eslint-disable no-await-in-loop */
        res = await request(`/manage/${method}`, { data: { pageNum, pageSize: 1000, data } });
        if (res.page.list) {
            exportExcel(header, res.page.list, filename.concat('.xlsx'));
            pageNum += 1;
        }
    } while (res.page.list);
    return true;
}
